package coder;

import java.nio.ByteBuffer;

import mission.Mission;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import pool.PoolManager;

/**
 * 服务器解码
 * @author Administrator
 *
 */
public class ServerDecoder implements ProtocolDecoder {

	private int length = 0;
	
	@Override
	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
			throws Exception 
	{
		if(length == 0)
		{
			if(in.limit() >= 4)
			{
				length = in.getInt();
			}
			else
			{
				return;
			}
		}
		if(in.limit() >= length)
		{
			Mission mission = PoolManager.missionPool.borrowObject();
			mission.serverId = in.get();
			mission.messageHead = in.getShort();
			byte[] bytes = new byte[length - 3];
			in.get(bytes);
			mission.bytes = ByteBuffer.wrap(bytes);
			mission.session = session;
			out.write(mission);
			length = 0;
		}
	}

	@Override
	public void finishDecode(IoSession session, ProtocolDecoderOutput out)
			throws Exception 
	{

	}

	@Override
	public void dispose(IoSession session) throws Exception 
	{

	}

}
